<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="充电站" prop="csName">
        <el-input
          v-model="queryParams.csName"
          placeholder="请输入充电站"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单时间" prop="dstime">
        <el-date-picker clearable
          v-model="selectedMonth"
          type="month"
          value-format="YYYY-MM"
          placeholder="请选择订单时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div style="display:flex;flex-wrap: wrap;height: 400px;width: 1000px">
      <div style="display:flex;flex-direction: column;width: 200px;margin-left: 20px">
        <div class="a">
          <div>充电费：</div>
          <div style="margin-top: -14px">{{totalcdMoney}}</div>
        </div>
        <div class="a">
          <div>服务费：</div>
          <div style="margin-top: -14px">{{totalserviceMony}}</div>
        </div>
        <div class="a">
          <div>营收合计：</div>
          <div style="margin-top: -14px">{{totalyingshouMoney}}</div>
        </div>
      </div>
      <div style="width: 300px;height: 200px;margin-left: 100px"><e-charts class="chart" :option="option2" /></div>
      <div style="width: 250px;height: 200px;margin-left: 50px"><e-charts class="chart" :option="option3" /></div>
    </div>
    <el-table v-loading="loading" :data="listAll"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="日期" align="center"  width="180">
        <template #default="scope">
          <!-- 直接使用charging_date字段 -->
          <span v-if="scope.row.dstime">
              {{ formatDate(scope.row.dstime) }}
            <!--                  {{ scope.row.charging_date }}-->
         </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="服务费" align="center" >
        <template #default="scope">
          {{ (scope.row.total_payment - scope.row.total_charging_kwh * 1.2).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="充电费" align="center"  >
        <template #default="scope" prop="total_payment">
          <span>{{ (scope.row.total_charging_kwh * 1.2).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="营收合计" align="center" prop="total_payment" />
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

  </div>
</template>

<script setup name="Ysorder">
import { listYsorder, getYsorder, delYsorder, addYsorder, updateYsorder } from "@/api/system/ysorder"
import { getChartData,selecttotal } from "@/api/system/yunyingrecord"
import {ref} from "vue";
import dayjs from 'dayjs' // 引入 dayjs
const { proxy } = getCurrentInstance()
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const listAll = ref([]);
const listst = ref([]);
const listChargeMoney = ref([]);
const listServiceMoney = ref([]);
const totalyingshouMoney = ref([])
const totalserviceMony = ref([])
const totalcdMoney = ref([])
const dayyingshouMoney = ref([])
const dayserviceMony = ref([])
const daycdMoney = ref([])
const totalDate = ref([])

const list = ref([])
const zhifufangshi = ref(["支付宝","微信"])
const all_wechat_count = ref([])
const all_alipay_count = ref([])
const lists = ref([])
// 替换原有的 selectedMonth 相关代码
const selectedMonth = ref(getCurrentMonth())
// const selectedMonth = (dayjs().format('YYYY-MM'))


const tableDatas = reactive({
  tableData: [],
  daychongidanmoney: null,
  dayfuwumoney: null,

})

const payType = reactive({
  "微信支付次数": all_wechat_count,
  "支付宝次数": all_alipay_count,
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    oNumber: null,
    oStationId: null,
    oAmount: null,
    oMoney: null,
    oHuiyuanId: null,
    oType: null,
    oStatus: null,
    oTime: [],
    csName: null,
    month: null,
    dtime: [],
    total_charging_kwh: 0,
    total_payment: 0,
    alipay_count: 0,
    wechat_count: 0,

  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)
const option3 = ref({
  tooltip: {
    trigger: 'item'
  },
  legend: {
    top: '5%',
    left: 'center'
  },
  series: [{
    name: '支付方式',
    type: 'pie',
    radius: ['40%', '60%'],
    avoidLabelOverlap: false,
    itemStyle: {
      borderRadius: 10,
      borderColor: '#fff',
      borderWidth: 2
    },
    label: {
      show: false,
      position: 'center'
    },
    emphasis: {
      label: {
        show: true,
        fontSize: 18,
        fontWeight: 'bold'
      }
    },
    labelLine: {
      show: false
    },
    data: [{ value: all_wechat_count, name: '微信支付' },
    { value: all_alipay_count, name: '支付宝支付' }],}
  ]
})

const option2 = ref({
  title: {
    text: '8月营收总额'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: totalDate
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '充电金额',
      type: 'line',
      data: dayyingshouMoney
    },
    {

      name: '服务费',
      type: 'line',
      data: dayserviceMony
    },

  ]
});


onMounted(()=>{
  selectedMonth.value = getCurrentMonth(); // 确保默认月份设置正确
  queryParams.value.month = selectedMonth.value;
  getList()
})
function formatDate(dateString) {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}

function getCurrentMonth() {
  const now = new Date();
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
}


/** 查询营收分析列表 */
function getList() {
  loading.value = true
  queryParams.value.month = selectedMonth.value;
  listYsorder(selectedMonth.value, queryParams.value.csName).then(response => {
    total.value = response.total
    // recordList.value = response
    if (response && response.length > 0) {

      console.log(91111111)
      listAll.value = response
      console.log(response)
      const month = selectedMonth.value.split('-')[1].replace(/^0/, ''); // 去掉前导零
      option2.value.title.text = `${month}月营收总额`;
       dayyingshouMoney.value = listAll.value.map(item =>item.total_payment)
      dayserviceMony.value = listAll.value.map(item => parseFloat((item.total_payment - item.total_charging_kwh).toFixed(2)))
       daycdMoney.value = listAll.value.map(item =>item.total_charging_kwh.toFixed(2))
        totalDate.value = listAll.value.slice(0,7).map(item =>item.dstime)
        totalyingshouMoney.value = listAll.value.slice(0,7).reduce((sum, item) => sum + item.total_payment, 0).toFixed(2);
        totalcdMoney.value = listAll.value.slice(0,7).reduce((sum,item) =>((sum+ (item.total_charging_kwh * 1.2))),0).toFixed(2);
        totalserviceMony.value = (totalyingshouMoney.value-totalcdMoney.value).toFixed(2);
          //支付宝次数
       queryParams.value.alipay_count = listAll.value.map((sum, item) =>item.alipay_count)
       console.log( queryParams.value.alipay_count)
          //微信次数
       queryParams.value.wechat_count = listAll.value.map((sum, item) =>item.wechat_count)
       console.log(queryParams.value.wechat_count)
      all_wechat_count.value = listAll.value.reduce((sum,item) =>sum+item.wechat_count,0)
      all_alipay_count.value = listAll.value.reduce((sum,item) =>sum+item.alipay_count,0)
      total.value = response.total
      loading.value = false
    } else {
      // 清空表格数据
      listAll.value = [];
      list.value = [];
      // queryParams.value.csName = null;
      // 清空图表数据
      totalDate.value = [];
      // totalData.value = [];
      // totalRechargeAmount.value = [];
      // totalRechargeTime.value = [];

      // 清空汇总数据
          listAll.value = response

          listChargeMoney.value = 0;
          listServiceMoney.value = 0;
          totalyingshouMoney.value = 0;
          totalcdMoney.value = 0;
          totalserviceMony.value = 0;

    }
  }).catch(error => {
    console.error("获取数据失败:", error);
    loading.value = false;
    // // 清空所有数据
    // queryParams.value = [];
    // listAll.value = [];
    // list.value = [];
    // ...其他清空操作...

  })
}



// 取消按钮
function cancel() {
  open.value = false
  reset()
}


// 表单重置
function reset() {
  form.value = {
    oId: null,
    oNumber: null,
    oStationId: null,
    oAmount: null,
    oMoney: null,
    oHuiyuanId: null,
    oType: null,
    oStatus: null,
    oTime: null
  }
  proxy.resetForm("ysorderRef")
}

/** 搜索按钮操作 */
function handleQuery() {

    queryParams.value.month = selectedMonth.value


  queryParams.value.pageNum = 1
  getList()
  // (queryParams.value.dtime || getCurrentMonth(),queryParams.value.csName
  // getListall();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.csName = ""; // 明确清空充电站
  selectedMonth.value = getCurrentMonth(); // 重置为当前月份
  queryParams.value.month = selectedMonth.value;
  // selectedMonth.value = getCurrentMonth(); // 重置为当前月份
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.oId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */


</script>
<style>
.chart {

  height: 300px;
}
.a{
  margin-top: 20px;
  height: 80px;
  text-align: center;
  line-height: 50px;
  background: linear-gradient(to right, rgba(0, 0, 255, 0.5), rgba(0, 128, 255, 0.5));
}
</style>
